package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@RestController
@RequestMapping("validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

//    @Autowired
//    private DefaultKaptcha dk;
    @Autowired
    private DefaultKaptcha dk;

//    获取验证码图片
    @RequestMapping("kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = dk.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        System.out.println(session.getAttribute(Constants.KAPTCHA_SESSION_KEY));
        //向客户端写出
        BufferedImage bi = dk.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

//验证码校验
    @RequestMapping("checkkaptchacode")
    public Result checkkaptchacode(@RequestParam("userkc")String userkc,HttpServletRequest request, HttpServletResponse response)
                                throws Exception{
        try {
            System.out.println(userkc);
            HttpSession session = request.getSession();
            String kc = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (kc.toLowerCase().equals(userkc.toLowerCase())){
                return new Result(true, "图形验证码正确");
            }else{
                return  new Result( false,"图形验证码不正确");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result( false,"图形验证码校验异常");
        }
    }


    /**
     * 提交预约功能中的发送验证码
     * @param telephone
     * @return
     */
    @RequestMapping("send2telephone")
    public Result send2telephone(@RequestParam("telephone")String telephone){

        try {
            //生成一个随机的验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            //给手机发送验证码
//            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code);

            //设置一个唯一的key
            String key = telephone+ RedisMessageConstant.SENDTYPE_ORDER;

            //将验证码存入到redis中，并设置一个10分钟的有效时间
            jedisPool.getResource().setex(key,60*10,code);

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }

    /**
     * 用户登陆的发送验证码
     *
     */
    @RequestMapping("send2Login")
    public Result send2Login(@RequestParam("telephone")String telephone){

        try {
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            //将验证码发送到手机
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code);

            //生成一个key
            String key = telephone+RedisMessageConstant.SENDTYPE_LOGIN;

            //将验证码存入到redis中，并且设置一个10分钟的有效时间
            jedisPool.getResource().setex(key,60*10,code);

            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }
}
